# -*- coding: utf-8 -*-
"""
LLM 服务主应用

@author: AI Assistant
"""
import sys
from pathlib import Path

# 添加当前目录到 Python 路径
current_dir = Path(__file__).resolve().parent
if str(current_dir) not in sys.path:
    sys.path.insert(0, str(current_dir))

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from loguru import logger
import uvicorn

from config import SERVICE_CONFIG, OLLAMA_CONFIG
from api.routes import router


# 创建 FastAPI 应用
app = FastAPI(
    title="LLM 水文模型参数调整服务",
    description="通过大语言模型多轮对话来修改水文模型参数",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# 注册路由
app.include_router(router)


@app.on_event("startup")
async def startup_event():
    """应用启动事件"""
    logger.info("🚀 LLM 服务启动中...")
    logger.info(f"  - Ollama 地址: {OLLAMA_CONFIG['base_url']}")
    logger.info(f"  - 模型: {OLLAMA_CONFIG['chat_model']}")
    logger.info(f"  - 服务地址: http://{SERVICE_CONFIG['host']}:{SERVICE_CONFIG['port']}")
    logger.info(f"  - API 文档: http://{SERVICE_CONFIG['host']}:{SERVICE_CONFIG['port']}/docs")


@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭事件"""
    logger.info("👋 LLM 服务关闭")


@app.get("/", summary="服务信息")
async def root():
    """服务根路径"""
    return {
        "service": "LLM 水文模型参数调整服务",
        "version": "1.0.0",
        "status": "running",
        "endpoints": {
            "docs": "/docs",
            "health": "/api/llm/health",
            "session": "/api/llm/session/load",
            "chat": "/api/llm/chat"
        }
    }


if __name__ == "__main__":
    import os
    
    # 检查是否启用 SSL
    use_ssl = os.getenv("USE_SSL", "false").lower() == "true"
    ssl_certfile = os.getenv("SSL_CERTFILE", "/etc/letsencrypt/live/ws.waterism.tech/fullchain.pem")
    ssl_keyfile = os.getenv("SSL_KEYFILE", "/etc/letsencrypt/live/ws.waterism.tech/privkey.pem")
    
    # 启动服务
    if use_ssl:
        logger.info(f"🔒 启用 HTTPS 模式")
        logger.info(f"  - 证书: {ssl_certfile}")
        logger.info(f"  - 密钥: {ssl_keyfile}")
        uvicorn.run(
            "main:app",
            host=SERVICE_CONFIG["host"],
            port=SERVICE_CONFIG["port"],
            reload=SERVICE_CONFIG["reload"],
            workers=SERVICE_CONFIG["workers"],
            log_level="info",
            ssl_certfile=ssl_certfile,
            ssl_keyfile=ssl_keyfile
        )
    else:
        logger.info(f"🔓 启用 HTTP 模式（如需 HTTPS，设置环境变量 USE_SSL=true）")
        uvicorn.run(
            "main:app",
            host=SERVICE_CONFIG["host"],
            port=SERVICE_CONFIG["port"],
            reload=SERVICE_CONFIG["reload"],
            workers=SERVICE_CONFIG["workers"],
            log_level="info"
        )

